﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Web;
using System.Collections;
using System.Threading;
using System.Web.Script.Serialization;

namespace HttpRequestTools
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private string fileName = String.Empty;
        private string filePath = String.Empty;
        private bool isApplicatonJson = false;
        private Dictionary<string, string> headersKeyValue = new Dictionary<string, string>();
        private Dictionary<string, string> bodysKeyValue = new Dictionary<string, string>();

        private delegate void ShowResponseText(string message);

        void SetMessage(string message)
        {
            txtResponse.Text = message;
        }

        void ShowMessage(string message)
        {
            if (this.InvokeRequired)
            {
                ShowResponseText d = new ShowResponseText(SetMessage);
                object[] arg = new object[] { message };//要传入的参数值      
                this.Invoke(d, arg);
                Thread.Sleep(1000);
            }
        }

        private void HttpPost(object postBodyString)
        {
            HttpPostBodyStr(postBodyString, "POST");
        }

        private void HttpPut(object postBodyString)
        {
            HttpPostBodyStr(postBodyString, "PUT");
        }

        private void HttpPostBodyStr(object postBodyString, string method)
        {
        
            string URL = txtUrl.Text.Trim();
            string postDataStr = postBodyString.ToString();
            string retString = "";

            Dictionary<string, string> PostVars = new Dictionary<string, string>();
            try
            {
                if (URL.IndexOf("http://") == -1) URL = "http://" + URL;

                postDataStr = postDataStr.Trim();

                Encoding encoding = Encoding.UTF8;

                string result = string.Empty;
                string postBody = string.Empty;

                WebClient wc = new WebClient();
                //获取head参数
                foreach (string key in this.headersKeyValue.Keys)
                {
                    wc.Headers.Add(key, headersKeyValue[key]);
                }

                foreach (string key in this.bodysKeyValue.Keys)
                {
                    PostVars.Add(key, bodysKeyValue[key]);
                }

                if (isApplicatonJson)
                {
                    wc.Headers[HttpRequestHeader.ContentType] = "application/json";
                }

                //获取body参数
                if (postDataStr.Trim().Length > 0)
                {
                    string[] paramAttr = postDataStr.Split('&');
                    foreach (string param in paramAttr)
                    {
                        string[] keyValue = param.Split('=');
                        if (keyValue.Length > 0)
                        {
                            PostVars.Add(keyValue[0].Trim(), keyValue[1].Trim());
                        }
                    }
                }

                if (postDataStr.Trim().Length > 0 && PostVars.Count == 0)
                {
                    byte[] postData = encoding.GetBytes(postDataStr);
                    byte[] responseData = wc.UploadData(URL, method, postData); // 得到返回字符流

                    retString = encoding.GetString(responseData);// 解码
                }
                else
                {
                    if (PostVars.Count > 0)
                    {
                        if (isApplicatonJson)
                        {
                            JavaScriptSerializer json = new JavaScriptSerializer();
                            string jsonString = json.Serialize(PostVars);

                            byte[] postData = encoding.GetBytes(jsonString);
                            byte[] responseData = wc.UploadData(URL, method, postData); // 得到返回字符流

                            retString = encoding.GetString(responseData);// 解码
                        }
                        else
                        {
                            System.Collections.Specialized.NameValueCollection PostParams = new System.Collections.Specialized.NameValueCollection();
                            foreach (string key in PostVars.Keys)
                            {
                                PostParams.Add(key, PostVars[key]);
                            }

                            byte[] byRemoteInfo = wc.UploadValues(URL, method, PostParams);
                            retString = System.Text.Encoding.Default.GetString(byRemoteInfo);
                        }
                    }
                }

                ShowMessage(retString);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "同志，出错误啦！");
            }
        }

        public string HttpGet(string URL, string postDataStr)
        {
            string retString = "";
            try
            {
                WebClient myClient = new WebClient();
                myClient.Encoding = Encoding.UTF8;
                StringBuilder sbParams = new StringBuilder();
                foreach (ListViewItem item in this.listView1.Items)
                {
                    string field = item.SubItems[0].Text;
                    string value = item.SubItems[1].Text;
                    if (sbParams.Length > 0)
                    {
                        sbParams.Append("&&");
                    }

                    sbParams.Append(field).Append("=").Append(value);
                }

                if (sbParams.Length > 0)
                {
                    URL = URL + "?" + sbParams.ToString();
                }
                if (postDataStr.Trim().Length > 0)
                {
                    if (postDataStr.IndexOf("?") != -1)
                    {
                        URL = URL + "&" + postDataStr;
                    }
                    else
                    {
                        URL = URL + "?" + postDataStr;
                    }
                }

                //获取head参数
                foreach (ListViewItem item in this.listViewHeader.Items)
                {
                    string field = item.SubItems[0].Text;
                    string value = item.SubItems[1].Text;
                    myClient.Headers.Add(field, value);
                }

                if (txtHeader.Text.Trim().Length > 0)
                {
                    string[] paramAttr = txtHeader.Text.Split('&');
                    foreach (string param in paramAttr)
                    {
                        string[] keyValue = param.Split('=');
                        if (keyValue.Length > 0)
                        {
                            myClient.Headers.Add(keyValue[0].Trim(), keyValue[1].Trim());
                        }
                    }
                }

                if (URL.IndexOf("http://") == -1 && URL.IndexOf("https://") == -1) URL = "http://" + URL;
                //linkLabel1.Text = URL.Replace("&","&&");

                string result = myClient.DownloadString(URL);
                return result;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "同志，出错误啦！");
            }

            return retString;

        }

        private void btnGet_Click(object sender, EventArgs e)
        {
            String responseText = String.Empty;
            try
            {
                responseText = HttpGet(txtUrl.Text.Trim(), txtRequest.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            txtResponse.Text = responseText;
        }

        private void btnPost_Click(object sender, EventArgs e)
        {
            isApplicatonJson = false;
            post();
        }

        private void btnPostJson_Click(object sender, EventArgs e)
        {
            isApplicatonJson = true;
            post();
        }

        private void post()
        {
            try
            {
                fillParams();
                string postString = txtRequest.Text.Trim();
                if (postString.Trim().Length > 0 && this.listView1.Items.Count > 0)
                {
                    MessageBox.Show("请在Request Text和Body参数列表这2种传参方式中选择一种！");
                    return;
                }

                string result = string.Empty;
                Thread t = new Thread(new ParameterizedThreadStart(HttpPost));
                t.Start(postString);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void put()
        {
            try
            {
                fillParams();
                string postString = txtRequest.Text.Trim();
                if (postString.Trim().Length > 0 && this.listView1.Items.Count > 0)
                {
                    MessageBox.Show("请在Request Text和Body参数列表这2种传参方式中选择一种！");
                    return;
                }

                string result = string.Empty;
                Thread t = new Thread(new ParameterizedThreadStart(HttpPut));
                t.Start(postString);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnPut_Click(object sender, EventArgs e)
        {
            isApplicatonJson = false;
            put();
        }

        private void btnPutJson_Click(object sender, EventArgs e)
        {
            isApplicatonJson = true;
            put();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {

        }

        private void fillParams()
        {
            headersKeyValue.Clear();
            bodysKeyValue.Clear();

            foreach (ListViewItem item in this.listViewHeader.Items)
            {
                string field = item.SubItems[0].Text.Trim();
                string value = item.SubItems[1].Text.Trim();
                headersKeyValue.Add(field, value);
            }

            foreach (ListViewItem item in this.listView1.Items)
            {
                string field = item.SubItems[0].Text.Trim();
                string value = item.SubItems[1].Text.Trim();
                bodysKeyValue.Add(field, value);
            }

            if (txtHeader.Text.Trim().Length > 0)
            {
                string[] paramAttr = txtHeader.Text.Split('&');
                foreach (string param in paramAttr)
                {
                    string[] keyValue = param.Split('=');
                    if (keyValue.Length > 0)
                    {
                        headersKeyValue.Add(keyValue[0].Trim(), keyValue[1].Trim());
                    }
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.TopMost = false;
            this.txtUrl.Text = "http://localhost:8080/pc/v1/trans/recharge";
            txtHeader.Text = "accessToken=779fb389ae1ff38d38c3d8b5ec92b63051294e";
            txtRequest.Text = "mobile=18601694368&amount=100&give=10&point=10";
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            string field = txtName.Text;
            string value = txtValue.Text;
            if (value == filePath) fileName = field;
            this.listView1.Items.Add(new ListViewItem(new string[] { field, value }));
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            this.listView1.Items.Clear();
        }

        private void btnAddHeader_Click(object sender, EventArgs e)
        {
            string field = txtHeadField.Text;
            string value = txtHeadValue.Text;
            this.listViewHeader.Items.Add(new ListViewItem(new string[] { field, value }));
        }

        private void btnClearText_Click(object sender, EventArgs e)
        {
            txtResponse.Text = "";
        }

        private void btnClearHeader_Click(object sender, EventArgs e)
        {
            listViewHeader.Items.Clear();
        }

        private void txtUrl_Leave(object sender, EventArgs e)
        {
            if (txtUrl.Text.IndexOf("http://") == -1 && txtUrl.Text.IndexOf("https://") == -1) txtUrl.Text = "http://" + txtUrl.Text;
        }

        StreamWriter writer;
        StreamReader reader;
        FileStream fs;

        private void btnSelect_Click(object sender, EventArgs e)
        {
            openFileDialog1.InitialDirectory = Application.ExecutablePath;
            //openFileDialog1.Filter = "All Files(*.*)|*.*";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                filePath = openFileDialog1.FileName;
                try
                {
                    fs = new FileStream(filePath, FileMode.Open);
                    reader = new StreamReader(fs);
                    txtValue.Text = filePath;
                }
                catch (Exception excep)
                {
                    MessageBox.Show(excep.Message);
                }
                finally
                {
                    reader.Close();
                    fs.Close();
                }
            }
        }

        private void saveFile() 
        {
            try
            {
                fs = new FileStream(filePath, FileMode.Create);
                writer = new StreamWriter(fs);
                writer.Write(filePath);
            }
            catch (Exception excep)
            {
                MessageBox.Show(excep.Message);
            }
            finally
            {
                writer.Flush();
                writer.Close();
                fs.Close();
            }
        }
    }
}
